package com.robot.search.controller;

import com.robot.search.entity.SearchResult;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Hujf
 * @title: SearchController
 * @date 2024-03-15 23:45
 * @description: TODO
 */
@Controller
public class SearchController {


    @Value("${file.index-dir}")
    private String INDEX_DIRECTORY;

    @GetMapping("/search")
    public ModelAndView testQueryParser(@RequestParam String textquery, Model model) throws Exception {
        List<SearchResult> results = new ArrayList<>();
        // 3.创建一个QueryParser对象
        QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
        // 4.使用queryParser对象创建一个Query
        Query query = queryParser.parse(textquery);

        Path path = new File(INDEX_DIRECTORY).toPath();
        Directory directory = FSDirectory.open(path);
        IndexReader indexReader = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        TopDocs topDocs = indexSearcher.search(query, 10); // Retrieve top 10 results
        //高亮处理
        SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<B>", "</B>");
        Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query));
        //取多少字
        highlighter.setTextFragmenter(new SimpleFragmenter(66));

        // Process search results
        // 输出结果
        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            SearchResult result = new SearchResult();
            Document hitDoc = indexSearcher.doc(topDocs.scoreDocs[i].doc);
            System.out.println("Content: " + hitDoc.get("title"));

            TokenStream tokenStream = new IKAnalyzer().tokenStream("Content", hitDoc.get("content"));
          //  String content = highlighter.getBestFragment(tokenStream, hitDoc.get("content"));
            String[] fragments = highlighter.getBestFragments(tokenStream, hitDoc.get("content"), 10);

            for(String fragment : fragments){
                System.out.println(fragment);
            }
         //   System.out.println(content);

            result.setTitle(hitDoc.get("title"));
         //   result.setContent(content);
            results.add(result);
            // results.add(hitDoc.get("title"));
        }

        directory.close();
        indexReader.close();

        model.addAttribute("results", results);
        return new ModelAndView("search");
    }
}
